package com.zjb.demo.common.util;

import cn.hutool.core.net.Ipv4Util;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.noear.snack.core.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IP地址查询
 *
 * @author 庄佳彬
 * @since 2023/12/25 21:45
 */
public class AddressUtils {
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
    // 未知地址
    public static final String UNKNOWN = "XX XX";
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    /**
     * 根据IP查询真实的地理位置
     *
     * @param ip 要查询的IP地址
     * @return 返回真实的地理位置，如果无法获取则返回UNKNOWN
     */
    public static String getRealAddressByIP(String ip) {
        // 内网不查询
        if (Ipv4Util.isInnerIP(ip)) {
            return "内网IP";
        }
        try {
            String rspStr = HttpUtil.get(IP_URL + "ip=" + ip + "&json=true");
            if (StringUtil.isEmpty(rspStr)) {
                log(ip);
                return UNKNOWN;
            }
            JSONObject obj = JSONUtil.parseObj(rspStr);
            String region = obj.getStr("pro");
            String city = obj.getStr("city");
            return String.format("%s %s", region, city);
        } catch (Exception e) {
            log(ip);
        }
        return UNKNOWN;
    }

    private static void log(String ip) {
        log.error("获取地理位置异常 {}", ip);
    }
}
